条款03:尽可能使用const

  • 修饰变量,使其不可改变

    1
    const int var = 3;

    此时var的值就不能改变了,因为这个特性,所以在声明的时候就要初始化,这样是不行的:

    1
    const int var;
  • 修饰指针

    可分为两种情况,指向常量的指针和常量指针

    1
    const int* p = &a;
  • 修饰迭代器

    C++的STL中既有vector<T>::iterator,也有vector<T>::const_iterator,而vector<T>::const_iterator即表示指向常量的迭代器,而另一种形式const vector<T>::iterator则表示这个迭代器的指向不可改变,即常量迭代器

  • 修饰类的成员函数

    • 有无const是可以构成成员函数的重载的

    • 如果某个类中有一个指针,如果在某个函数中确实改动了p所指向的内容,那么最好就不要加上const,反过来,如果加上了const就不要改变成员变量,包括它所指向的值

    • const成员函数和非const成员函数中避免重复

      有没有加const是构成函数重载的,但通常这种重载的相似度很高:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      class TestBlock {
      private:
      string text;
      public:
      ...
      const char& operator[](size_t position) const {
      ...
      return text[position];
      }
      char& operator[](size_t position) {
      ...
      return text[position];
      }
      }

      一个好的方法就是在非const版本的成员函数中调用const版本的成员函数:

      1
      2
      3
      char& operator[](size_t position) {
      return const_cast<char&>(static_cast<const TestBlock&> (*this)[position]);
      }

      正如上面代码所示,进行了两次转换,一次是把非const对象转成const对象,使用static_cast<const TestBlock&>,另一次是在返回值时,将const char&通过const_cast<char&>转换成char&